<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
	<title>Template Designer</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
	<meta name="author" content="yangzheng@evmtv.com"/>
	<meta name="description" content="EMSP_CMS.TemplateDesigner"/>
	<meta name="x_class" content="com.evmtv.emsp_cms.templateDesigner"/>
	<link href="../swatlib/SwatWeb/spark/spark.css" rel="stylesheet" type="text/css"/>
</head>

<style type="text/css">
body							{padding:0px;margin:0px;color:#ccc;font:normal 14px tahoma;background:#34383E;overflow:hidden}
#div							{border:1px dotted #cc0}

/** UI */
.Panel_H						{background:#5F686D url(assets/images/panel_orn_h.png) repeat-y;border-left:1px solid #828A90;border-top:1px solid #828A90;border-right:1px solid #0a0a0a;border-bottom:1px solid #0a0a0a}
.Panel_V						{background:#5F686D url(assets/images/panel_orn_v.png) repeat-x;border-left:1px solid #828A90;border-top:1px solid #828A90;border-right:1px solid #0a0a0a;border-bottom:1px solid #0a0a0a}

/** named */
#eWorkspace						{position:absolute;z-index:0;overflow:auto}
#eToolBar						{position:absolute;width:400px;height:80px;left:0px;top:0px;z-index:0;background:#5F686D url(assets/images/panel_toolbar_bkg.png)}
#ePanel_Menu					{position2:absolute;float:left;width:400px;height:80px;background:#5F686D url(assets/images/panel_menu_bkg.png) no-repeat}
#eMenuBar						{position:absolute;width:300px;height:24px;left:25px;top:47px;z-index:20;border2:1px solid #00c}
#ePanel_QuickBar				{position2:absolute;float:left;width:auto;height:80px}
#ePanel_Info					{position2:absolute;float:left;width:400px;height:40px}
#eProjectWnd					{position:absolute;width:280px;height:400px;left:0px;top:76px;z-index:10;padding-top:10px}


.eProjectWnd_Sheet				{width:100%;height:100%;background:#5F686D}
#eSheet_TemplateProp			{background:#20292E}
#eSheet_ElemStruct				{background:#303138}
#eSheet_Comp					{background:#20292E}
#eSheet_Comp_Content			{width:100%}
#eHotCompIndicator				{position:absolute;left:0px;top:0px;width:48px;height:48px;z-index:30;border2:1px solid #c00}
#eSheet_CompProp				{background:#20292E}

/** Template */
.T_Normal						{position:absolute;z-index:0;background:#5F686D;overflow2:hidden;border:2px solid #111}
.T_Normal .grid					{position:absolute;z-index:1;background:url(assets/images/ui_grid_dot_20x20.png)}
.T_Normal .safearea				{position:absolute;z-index:2;background:;border:40px solid #114a11}
.T_Normal .code					{position:absolute;z-index:3;background:#333;border:0px solid #114a11;display:none}
.T_Normal .codearea				{position:absolute;z-index:3;background:#181818;border:0px;overflow:auto;font:normal 14px Consolas;color:#fff}

/** Component in Template */
.T_Component					{position:absolute;z-index:20;border:1px dashed #eee;background2:#001c38;overflow2:hidden}
.T_Component div				{position:absolute}
.T_Component .icon				{left:0px;top:0px;width:48px;height:48px}
.T_Component .info				{left:55px;top:15px;height:20px;background2:#f00;font:normal 11px tahoma;color:#fff;border2:1px solid #ff0}

/** Standard Controls */
.CMS_CtrlRow					{border2:1px solid #c00;height:40px;font:normal 16px Consolas;text-align:center}
.CMS_CtrlRow div				{float:left;font:normal 16px Tahoma}
.CMS_CtrlRow .caption			{margin-right:5px;padding-top:3px;color:#eee;width:100px;text-align:right}
.CMS_CtrlRow .cap2				{margin-right:5px;margin-left:5px;padding-top:3px;color:#eee;text-align:right}
.CMS_CtrlRow input				{width:100%;height:25px;font:normal 16px Consolas;color:#aaa;background:#333;border-left:1px solid #111;border-top:1px solid #111;border-right:1px solid #444;border-bottom:1px solid #444}
.CMS_CtrlRow textarea			{width:100%;font:normal 16px Consolas;color:#aaa;background:#333;border-left:1px solid #000;border-top:1px solid #000;border-right:1px solid #405253;border-bottom:1px solid #405253}
.CMS_CtrlRow button				{width:120px;height:32px;font:normal 16px 微软雅黑;margin-left:10px;margin-right:10px}

/** Componets item */
.CMS_ComponentItem				{float:left;width:68px;height:75px;text-align2:center;border2:1px solid #c00}
.CMS_ComponentItem_Icon			{width:48px;height:48px;margin-left:5px;border2:1px solid #c00}
.CMS_ComponentItem_Text			{width:60px;height:12px;text-align:center;font:normal 12px Consolas;color:#aaa}

.CMS_Button_Normal				{width:100px;height:23px;border:0px;zoom:1;outline:none;background:url(assets/images/btn_normal.png) no-repeat 0 0}
.CMS_Button_Normal_over			{width:100px;height:23px;border:0px;zoom:1;outline:none;background:url(assets/images/btn_normal.png) no-repeat 0 -23}
.CMS_Button_Normal_down			{width:100px;height:23px;border:0px;zoom:1;outline:none;background:url(assets/images/btn_normal.png) no-repeat 0 -46}

/** spark override */
.SxSheetGroup					{}
.SxSheetGroup_TabBar			{width:100%;height:16px;font:normal 12px Tahoma;text-align:left}
.SxSheetGroup_TabBar div		{float:left;white-space:nowrap;height:22px;line-height:22px;cursor:default}
.SxSheetGroup_Tab				{padding:0px 8px 0px 8px;color:#888;background:url(assets/images/spark_sheetgroup_bar.png) no-repeat 0 0;border:1px solid #000}
.SxSheetGroup_Tab_h				{padding:0px 8px 0px 8px;height:22px;color:#fff;background:url(assets/images/spark_sheetgroup_bar.png) no-repeat 0 -24;border:1px solid #000}
.SxSheetGroup_Tab_Active		{padding:0px 8px 0px 8px;height:22px;color:#ccc;background:url(assets/images/spark_sheetgroup_bar.png) no-repeat 0 -48;border:1px solid #000}
.SxSheetGroup_Content			{width:100%;height:100%;overflow:hidden;border:2px inset #5F686D;padding:0px}

.SxDialog						{position:absolute;display:none}
.SxDialog_Cover					{position:absolute;left:0px;top:0px;background:#444}
.SxDialog_Frame					{position:absolute;left:0px;top:0px;background:#5F686D;border:2px solid #000}
.SxDialog_Title					{background:#111;border-left:1px solid #555;border-top:1px solid #555;border-right:1px solid #000;border-bottom:1px solid #000;font:normal 16px 微软雅黑}

.SxStackList_Common				{font:normal 14px Consolas;color:#888}
.SxStackList_Pane				{width:100%}
.SxStackList_Pane_Title			{padding-left:10px;height:27px;background:url(assets/images/spark_stackList_bar.png) repeat-x 0 0;border:0px;border-left:1px solid #000;border-right:1px solid #000;line-height:27px;}
.SxStackList_Pane_Title_h		{padding-left:10px;height:27px;background:url(assets/images/spark_stackList_bar.png) repeat-x 0 -54;color:#cc0;border:0px;border-left:1px solid #000;border-right:1px solid #000;line-height:27px}
.SxStackList_Pane_Title_Active	{padding-left:10px;height:27px;background:url(assets/images/spark_stackList_bar.png) repeat-x 0 -27;color:#fff;border:0px;border-left:1px solid #000;border-right:1px solid #000;line-height:27px}
.SxStackList_Pane_Content		{border:0px solid #666;background:url(assets/images/spark_stackList_group_bkg.png)}

.SxQuickTips_Frame				{position:absolute;background:#f4f9be;display:none;border:1px solid #443f01;padding:3px 20px 3px 20px;font:normal 14px Tahoma;color:#000;z-index:65000}

.SxActiveTree_Item .CI_Close		{float:left;width:20px;height:23px;background:url(assets/images/spark_activetree_ctrlIcon.png) no-repeat 0 0}
.SxActiveTree_Item .CI_CloseH		{float:left;width:20px;height:23px;background:url(assets/images/spark_activetree_ctrlIcon.png) no-repeat 0 -20}
.SxActiveTree_Item .CI_Open		{float:left;width:20px;height:23px;background:url(assets/images/spark_activetree_ctrlIcon.png) no-repeat 0 -40}
.SxActiveTree_Item .CI_OpenH		{float:left;width:20px;height:23px;background:url(assets/images/spark_activetree_ctrlIcon.png) no-repeat 0 -60}
.SxActiveTree_Item .lineH			{float:left;background:url(assets/images/spark_activetree_hotitem_bkg.png) no-repeat left 0;color:#ccc}
.SxActiveTree_Item .lineSelected	{float:left;background:url(assets/images/spark_activetree_hotitem_bkg.png) no-repeat left -23;color:#fff}
.SxActiveTree_Item .REdgeH			{float:right;width:3px;height:23px;background:url(assets/images/spark_activetree_hotitem_bkg.png) no-repeat right 0}
.SxActiveTree_Item .REdgeSelected	{float:right;width:3px;height:23px;background:url(assets/images/spark_activetree_hotitem_bkg.png) no-repeat right -23}

.SxPropertyEditor				{position:absolute;width:100%;height:auto;border2:1px solid #0c0}
.SxPropertyEditor .key			{float:left;width:40%;height:28px;background:url(assets/images/propeditor_key_bkg.png) repeat-x bottom right;line-height2:25px;font:normal 14px Consolas;color:#888;padding-left:5px;padding-top:3px}
.SxPropertyEditor .value		{float:left;width:60%;height:28px;background:url(assets/images/propeditor_value_bkg.png) repeat-x bottom;line-height:25px;color:#888;border2:1px solid #c00}
.SxPropertyEditor .input		{height:24px;background:#13191c;border:0px;color:#02a4e0;font:normal 14px Segoe UI}
.SxPropertyEditor .inputRO		{height:24px;background:#13191c;border:0px;color:#444;font:normal 14px Segoe UI}
.SxPropertyEditor .select		{height:30px;background:#13191c;border:0px;color:#02a4e0;font:normal 16px Segoe UI}
.SxPropertyEditor .selectRO		{height:24px;background:#13191c;border:0px;color:#444;font:normal 14px Segoe UI}


.SxMainMenu						{position:absolute;font:normal 14px 微软雅黑;cursor:default}
.SxMainMenu .content			{background:#b7c0c5;color:#111;border:2px solid #111}
.SxMainMenu .topItem			{height:20px;line-height:20px;text-align:center}
.SxMainMenu .topItemHover		{height:20px;line-height:20px;text-align:center;background:#394546}
.SxMainMenu .item				{height:20px;line-height:20px;text-align:left;background:#b7c0c5;padding:5px 0px 5px 0px}
.SxMainMenu .hover				{height:20px;line-height:20px;text-align:left;background:#5d6a73;color:#fff;padding:5px 0px 5px 0px}
.SxMainMenu .separator			{height:1px;background:#b7c0c5;border-bottom:2px solid #8f9ba1;font-size:0px}
.SxMainMenu .check				{position2:absolute;float:left;width:22px;height:20px;left:0px;top:0px;height:20px;background:url(assets/images/spark_menu_icon_check.png) no-repeat 0 0}
.SxMainMenu .text				{position2:absolute;float:left;height:20px;left:0px;top:0px;height:20px;line-height:20px;background:;}
</style>

<!--import libs-->
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/swat3.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/spark.common.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/Menu.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/Group.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/SheetGroup.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/StackList.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/ActiveTree.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/border.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/Dialog.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/QuickTips.js"></script>
<script type="text/javascript" language="javascript" src="../swatlib/SwatWeb/spark/ColorPicker.js"></script>

<!--import data-->
<script type="text/javascript" language="javascript" src="assets/data/D_global.js"></script>
<script type="text/javascript" language="javascript" src="assets/data/D_config.js"></script>
<script type="text/javascript" language="javascript" src="assets/data/D_components.js"></script>
<script type="text/javascript" language="javascript" src="assets/data/D_code.js"></script>
<script type="text/javascript" language="javascript" src="assets/data/D_menus.js"></script>

<script type="text/javascript">

/////////////
scumix.swat.spark.PropertyEditor = $.newClass();
scumix.swat.spark.PropertyEditor.prototype =
{
	constructor: function( P )
	{
		this.id = $.makeGlobalId( 'SxPropertyEditor' );

		this.width = P && P.width || '100%';
		this.height = P && P.height || '100%';
		this.animSpeed = P ? $.defaultValue( P.animSpeed , 1 ) : 1;

		this.properties = new Array();

		this.EContainer = $E(P.container) || null;
		this.EFrame = null;
		this.EContent = null;
		this.EContentTB = null;

		this.doCreate( P );
	},

	doCreate: function( P )
	{
		with( this )
		{
			if( !EContainer ) return false;
			EFrame = $.createElement({type:'div',id:id + '_Frame',css:'',attr:{className:'SxPropertyEditor'}});
			EContainer.appendChild( EFrame );
		}
	},

	clear: function()
	{
		with( this )
		{
			for( var i in properties )
			{
				var it = properties[i];
				it.eValue.removeChild( it.eCtrl );
				EFrame.removeChild( it.eKey );
				EFrame.removeChild( it.eValue );
				delete properties[i];
			}
		}

		return this;
	},

	addProperty: function( P, S )
	{
		with( this )
		{
			var K, V, C
				,rid = id + '_R' + properties.length
				,DV = P.defaultValue || ''
				;

			K = $.createElement({type:'div',id:rid,css:'',attr:{className:'key',exDragable:0,exSizable:0,exSizeDir:'R',innerHTML:P.text}});
				$(K).event( 'resize', function()
						{
							$(this.id+'_V').css('width', $(EFrame).css('width') - $(this).css('width'));
							$(this.id+'_C').css('width', $(EFrame).css('width') - $(this).css('width'));
						})
					;
			EFrame.appendChild( K );

			V = $.createElement({type:'div',id:rid + '_V',css:'',attr:{className:'value'}});

			switch( P.type )
			{
				default:
				case 'text':
				{
					C = $.createElement({type:'input',id:rid + '_C',css:'',attr:{xData:P,xAssocCtrl:S,className:P.readOnly?'inputRO':'input',type:'text',value:DV,lastValue:S[P.field],readOnly:P.readOnly?1:0}});
					$(C)
						.css('width','100%')
						.event('blur',
							function()
							{
								with( this )
								{
									if( xData.type )
									{
										if( !$.validate.test( value, xData.type ))
										{
											Designer.quickTips.warning( '数据格式不正确' );
											value = lastValue;
										}
										else
										{
											if( value != lastValue )
											{
												lastValue = value;
												if( xAssocCtrl.setProperty ) xAssocCtrl.setProperty( xData.field, value );
											}
										}
									}
								}
							})
					.event('keydown',
							function()
							{
								var K = $.getEvent().keyCode;
								if( K == 13 ) this.blur();
							})
						;

					// 若有关联数据, 则调用组件取属性方法
					if( P.field ) C.value = S.getProperty( P );
				} break;

				case 'color':
				{
					C = $.createElement({type:'input',id:rid + '_C',css:'',attr:{xData:P,xAssocCtrl:S,className:P.readOnly?'inputRO':'input',type:'text',value:DV,lastValue:S[P.field],readOnly:P.readOnly?1:0}});
					$(C)
						.css('width','100%')
						.event('blur',
							function()
							{
								with( this )
								{
									if( xData.type )
									{
										if( !$.validate.test( value, xData.type ))
										{
											Designer.quickTips.warning( '数据格式不正确' );
											value = lastValue;
										}
										else
										{
											if( value != lastValue )
											{
												lastValue = value;
												if( xAssocCtrl.setProperty ) xAssocCtrl.setProperty( xData.field, value );
											}
										}
									}
								}
							})
					.event('keydown',
							function()
							{
								var K = $.getEvent().keyCode;
								if( K == 13 ) this.blur();
							})
					.event('mousedown',
							function()
							{
								Designer.colorPicker.show(this);
							})
						;

					// 若有关联数据, 则调用组件取属性方法
					if( P.field ) C.value = S.getProperty( P );
				} break;

				case 'select':
				{
					C = $.createElement({type:'div',id:rid + '_C',css:'position:absolute;overflow:hidden',attr:{className:'input'}});
					oSelect = $.createElement({type:'select',id:rid + '_Select',css:'width:162px;margin:-2px',attr:{xData:P,xAssocCtrl:S,className:P.readOnly?'selectRO':'select'}});
					for( var i in P.options ) oSelect.options.add( new Option( P.options[i].text, P.options[i].value ));
					C.appendChild( oSelect );
					$(oSelect)
						.event('change',
							function()
							{
								with( this )
								{
									if( xAssocCtrl.setProperty ) xAssocCtrl.setProperty( xData.field, $(this).value()[0]);
								}
							})
						;
					if( P.field ) $(oSelect).value( S.getProperty( P ));
				} break;

				case 'image':
				{
					C = $.createElement({type:'input',id:rid + '_C',css:'',attr:{xData:P,xAssocCtrl:S,className:P.readOnly?'inputRO':'input',type:'text',value:DV,lastValue:S[P.field],readOnly:P.readOnly?1:0}});
					$(C)
					.css('width','100%')
					.event('blur',
						function()
						{
							with( this )
							{
								if( value != lastValue )
								{
									lastValue = value;
									if( xAssocCtrl.setProperty ) xAssocCtrl.setProperty( xData.field, value );
								}
							}
						})
					.event('keydown',
						function()
						{
							var K = $.getEvent().keyCode;
							if( K == 13 ) this.blur();
						})
					.event('mousedown', function()
						{
							var r = Designer.aux.browseResource();
							if( !r ) return;
							with( this )
							{
								value = r.url;
								if( xAssocCtrl.setProperty ) xAssocCtrl.setProperty( xData.field, r.url );
							}
						})
						;

					// 若有关联数据, 则调用组件取属性方法
					if( P.field ) C.value = S.getProperty( P );

				} break;
			}

			V.appendChild( C );
			EFrame.appendChild( V );
			$(C).css('width','160px');
			var o = {id:P.id, rid:rid, eKey:K, eValue:V, eCtrl:C}
			properties[o.id] = o;
		}

		return this;
	},

	getProperty: function( ID )
	{
		with( this )
		{
			return properties[ID] ? $(properties[ID].eCtrl).value() : '';
		}
	},

	setProperty: function( ID, V )
	{
		with( this )
		{
			if( properties[ID] )
			{
				$(properties[ID].eCtrl).value( V ).attr('lastValue', V);
			}
		}

		return this;
	},

	// 更新属性值
	// P: {src:源对象,keys:[字段数组]}
	updateProperty: function( P )
	{
		with( this )
		{
			for( var i=0; i<P.keys.length; i++ )
			{
				if( properties[P.keys[i]] )
				$(properties[P.keys[i]].eCtrl).value( P.src[P.keys[i]] ).attr('lastValue', P.src[P.keys[i]]);
			}
		}

		return this;
	}
}

// 类注册
Namespace.register( 'emsp_cms' );
//
// 组件
//
emsp_cms.Component = $.newClass();
emsp_cms.Component.prototype =
{
	constructor: function( P )
	{
		this.id = P.id || $.makeGlobalId( 'xComp' );
		this.classType = 'Component';
		this.isNewCreate = P.isNewCreate === 0 ? 0 : 1;

		// 属性
		this.groupID = P.groupID || 0;
		this.compID = P.compID || 0;
		this.componentName = '';
		this.text = P.text || '';
		this.left = P.left || 0;
		this.top = P.top || 0;
		this.width = P.width || 280;
		this.height = P.height || 100;
		this.fontSize = P.fontSize || 24;
		this.textAlign = P.textAlign || '';
		this.background = P.background || '';
		this.backgroundColor = P.backgroundColor || '#001c38';
		this.backgroundImage = P.backgroundImage || '';
		this.backgroundRepeat = P.backgroundRepeat || '';
		this.backgroundAttachment = P.backgroundAttachment || '';
		this.backgroundPosition = P.backgroundPosition || '';
		this.color = P.color || '#ccc';
		this.fontSize = P.fontSize || '';
		this.fontStyle = P.fontStyle || '';
		this.fontWeight = P.fontWeight || '';
		this.zIndex = P.zIndex || 1;

		// 持久属性
		this.persistentProperty =
		['groupID','compID','id','componentName','text','left','top','width','height','fontSize','fontStyle','fontWeight','textAlign','background','backgroundColor','backgroundImage','backgroundRepeat','backgroundAttachment','backgroundPosition','color','zIndex']

		// 私有
		this.data = 0;
		this.parentTemplate = 0;
		this.elemComponent = 0;
		this.elemTips = 0;
		this.elemIcon = 0;
		this.elemTag = 0;

		this.onGetHtmlCode = 0;
		this.onGetJsCode = 0;
		this.onSetProperty = 0;

		this.doCreate( P );
	},

	doCreate: function( P )
	{
		with( this )
		{
			var T = Designer.templateManager.curTemplate.elemTemplate
				,data = D = DS_Components.nodes[groupID].comps[compID];

			componentName = D.text;
			onGetHtmlCode = D.onGetHtmlCode || 0;
			onGetJsCode = D.onGetJsCode || 0;
			onSetProperty = D.onSetProperty || 0;

			if( D.onCreate )
			{
				elemComponent = D.onCreate( {id:id, x:left, y:top, w:width, h:height, xJsObject:this, isNewCreate:isNewCreate} );
			}

			else
			{
				elemComponent = $.createElement({type:'div',id:id,css:'',attr:{xJsObject:this, className:'T_Component', xText:D.text,exDragable:'1',exTopOnDrag:'1',exSizable:'1'}});
					$(elemComponent).css('left', left).css('top', top).css('width', width).css('height', height).css('backgroundColor', backgroundColor).css('opacity',60);

				elemIcon = $.createElement({type:'div',id:id + '_Icon',css:'',attr:{className:'icon',exPass:'1'}});
					elemIcon.style.background = 'url(' + DS_Components.nodes[groupID].glyphSrc + ') no-repeat -' + D.glyph.x + ' -' + D.glyph.y;
					elemComponent.appendChild(elemIcon);

				elemTips = $.createElement({type:'div',id:id + '_T',css:'',attr:{className:'info',exPass:'1'}});
					$(elemTips).css('opacity',40);
					elemTips.innerHTML = D.text + ' [' + left + ':' + top + ' - ' + width + ':' + height + ']';
					elemComponent.appendChild(elemTips);

				/*elemTag = $.createElement( {type:'div', id:id + '_Tag', css:'position:absolute;width:100px;height:20px;background:#c00', attr:{xGroup:'tag', className:'T_Component_Tag',exPass:'1'}} );
				$(elemTag).css('width', 200 )
					.css('height', 20)
					.css('left', -10)
					.css('top', -20)
					;
					elemComponent.appendChild( elemTag );*/
			}

			// 若组件非新创建, 则重新设置属性
			if( !isNewCreate )
			{
				var o = $(elemComponent);
				for( var i in persistentProperty )
				{
					this[persistentProperty[i]] = P[persistentProperty[i]];
					if( this[persistentProperty[i]] == undefined ) this[persistentProperty[i]] = '';
					if( $.validate.isCssAttr( persistentProperty[i] )) o.css( persistentProperty[i], this[persistentProperty[i]] );
					if( D.onSetProperty ) D.onSetProperty.call( this, persistentProperty[i], this[persistentProperty[i]] );
				}
			}

			$(elemComponent)
				.event( 'mousedown', function()
					{
						var E = $.getEvent();

						with( this.xJsObject.parentTemplate )
						{
							// 设为当前组件
							setCurrentComponent( this.xJsObject );

							// 计算可拖动区域
							var r = $(elemTemplate).css('width') - $(this).css('width') - 4,
							b = $(elemTemplate).css('height') - $(this).css('height') - 4;
							this.xJsObject.zIndex = this.style.zIndex;
						}

						// 未按 alt 键时, 设置限定移动范围
						// 按下 alt 键时, 可移动至模板区域外
						if( !E.altKey )
							$(this).attr('exDragRect', {left:0,top:0,right:r,bottom:b});
						else
							$(this).attr('exDragRect', 0);

						// 更新组件树
						with( Designer.templateManager.curTemplate )
						{
							if( lastComponent != this.xJsObject )
							{
								lastComponent = this.xJsObject;
								Designer.atree_ElemStruct.rootItem.setCurItem( Designer.atree_ElemStruct.rootItem.getChildByProperty( 'id', this.xJsObject.id ));
								Designer.control.setCurControl( this.xJsObject );
							}
						}
					})
				.event( 'resize', function()
					{
						var E = $.getEvent();
						var o = $(this), el = $E(this.id + '_T');
						if( E.ctrlKey || Designer.templateManager.curTemplate.m_snapToGrid )
						{
							with( Designer.workspace )
								o.css('width', parseInt( o.css('width') / gridSize ) * gridSize ).css( 'height', parseInt( o.css('height') / gridSize ) * gridSize );
						}

						if( el ) el.innerHTML = o.attr('xText') + ' [' + o.css('left') + ':' + o.css('top') + ' - ' + o.css('width') + ':' + o.css('height') + ']';

						// 更新属性
						with( this.xJsObject )
						{
							width = o.css('width');
							height = o.css('height');
							Designer.control.updateProperty( {src:this.xJsObject, keys:['width','height']} );
						}
					})
				.event( 'move', function()
					{
						var E = $.getEvent();
						var o = $(this), el = $E(this.id + '_T');
						if( E.ctrlKey || Designer.templateManager.curTemplate.m_snapToGrid )
						{
							with( Designer.workspace )
								o.css('left', parseInt( o.css('left') / gridSize ) * gridSize ).css( 'top', parseInt( o.css('top') / gridSize ) * gridSize );
						}
						if( el ) el.innerHTML = o.attr('xText') + ' [' + o.css('left') + ':' + o.css('top') + ' - ' + o.css('width') + ':' + o.css('height') + ']';

						// 更新属性
						with( this.xJsObject )
						{
							left = o.css('left');
							top = o.css('top');
							Designer.control.updateProperty( {src:this.xJsObject, keys:['left','top']} );
						}
					});
		}
	},

	getProperty: function( P )
	{
		with( P )
		{
			return this[field] == undefined ? '' : this[field];
		}
	},

	setProperty: function( F, V )
	{
		with( this )
		{
			this[F] = V;
			if( $.validate.isCssAttr( F )) $(elemComponent).css( F, V );

			switch( F )
			{
				case 'backgroundColor':
					if( V ) elemComponent.style.backgroundColor = V;
					else elemComponent.style.background = '';
					break;

				case 'backgroundImage':
					elemComponent.style.backgroundImage = 'url(' + V + ')';
					break;
			}

			if( onSetProperty ) onSetProperty( F, V );
		}
	},

	getHtmlCode: function()
	{
		with( this )
		{
			// 组件自定义
			if( $.isFunction( onGetHtmlCode )) return onGetHtmlCode(this);

			// 默认
			var E;
			E = '<div id="' + id + '" name="' + id + '" CMS_Class="' + data.clsName + '" style="left:' + left + 'px;top:' + top + 'px;width:' + width + 'px;height:' + height + 'px'
				+ ';font-size:' + fontSize + 'px;color:' + color + ';backgroundColor:' + backgroundColor + ';z-index:' + zIndex + '">';
			E += '</div>';
			return E;
		}
	},

	getJsCode: function( A )
	{
		with( this )
		{
			return $.isFunction( onGetJsCode ) ? onGetJsCode(this, A) : '';
		}
	},

	repaint: function()
	{

	}
}

//
// 模板
//
emsp_cms.Template = $.newClass();
emsp_cms.Template.prototype =
{
	constructor: function(  P )
	{
		this.id = P.id || $.makeGlobalId( 'xTemp' );
		this.classType = 'Template';
		this.isNewCreate = P.isNewCreate === 0 ? 0 : 1;

		this.animSpeed = $.defaultValue( P.animSpeed , 1 );

		// 属性
		this.templateName = P.templateName || '';
		this.left = P.left || Designer.workspace.factLeft;
		this.top = P.top || Designer.workspace.factTop;
		this.width = P.width || 0;
		this.height = P.height || 0;
		this.background = P.background || '';
		this.color = P.color || '#ccc';
		this.backgroundColor = P.backgroundColor || '#5F686D';
		this.backgroundImage = P.backgroundImage || '';
		this.backgroundRepeat = P.backgroundRepeat || '';

		this.alias = P.alias || '';
		this.author = P.author || '';
		this.desc = P.desc || '';
		this.layout = P.layout || '0';
		this.definition = P.definition || 'HD';

		// 持久属性
		this.persistentProperty =
		['id','templateName','left','top','width','height','background','backgroundColor','backgroundImage','backgroundRepeat','color','alias','author','desc','layout','definition']

		// 私有
		this.parentManager = 0;
		this.elemTemplate = 0;
		this.elemGrid = 0;
		this.elemSA = 0;
		this.elemTag = 0;
		this.elemCode = 0;
		this.elemCodeArea = 0;

		this.components = new Array();
		this.curComponent = 0;
		this.lastComponent = 0;

		this.m_showGrid = 1;
		this.m_showSA = 1;
		this.m_showCode = 1;
		this.m_snapToGrid = 0;
		this.m_showAnim = 1;

		this.doCreate( P );
	},

	doCreate: function( P )
	{
		with( this )
		{
			// 创建关联 DOM 对象
			elemTemplate = $.createElement( {type:'div', id:id + '_Wnd', css:'', attr:{xJsObject:this, xGroup:'template', className:'T_Normal',exDragable:'1',exTopOnDrag:'1',exSizable:'1'}} );
				$(elemTemplate).css('width', width).css('height', height).css('backgroundColor', backgroundColor )
					.css('left', Designer.workspace.factLeft).css('top', Designer.workspace.factTop)
					.event( 'resize', function()
						{
							var I = $(this);
							with( this.xJsObject )
							{
								$(elemGrid).css('width', I.css('width')-4).css('height', I.css('height')-4);
								$(elemSA).css('width', I.css('width')-4).css('height', I.css('height')-4);
								$(elemCode).css('width', I.css('width')-4).css('height', I.css('height')-4);
								$(elemCodeArea).css('width', I.css('width')-12).css('height', I.css('height')-38);

								// 更新属性
								width = I.css('width');
								height = I.css('height');
								Designer.control.updateProperty( {src:this.xJsObject, keys:['width','height']} );
							}
						})
					.event( 'mousedown', function()
						{
							Designer.templateManager.setCurrentTemplate( this.xJsObject );
							if( $.getTarget().xGroup == 'template' )
							{
								this.xJsObject.setCurrentComponent(null);
								Designer.control.setCurControl( this.xJsObject );
							}
						})
					.event( 'move', function()
					{
						if( $.getTarget() != this ) return;
						var o = $(this);
						with( this.xJsObject )
						{
							left = o.css('left');
							top = o.css('top');
							Designer.control.updateProperty( {src:this.xJsObject, keys:['left','top']} );
						}
					});

			// 若模板非新创建, 则重新设置属性
			if( !isNewCreate )
			{
				var o = $(elemTemplate);
				for( var i in persistentProperty )
				{
					this[persistentProperty[i]] = P[persistentProperty[i]];
					if( $.validate.isCssAttr( persistentProperty[i] ))
					{
						o.css( persistentProperty[i], this[persistentProperty[i]] );
					}
				}
			}

			/*elemTag = $.createElement( {type:'div', id:id + '_Grid', css:'position:absolute;width:200px;height:30px;background:#c00', attr:{xGroup:'tag', className:'T_Normal_Tag',exPass:'1'}} );
				$(elemTag).css('width', 200 )
					.css('height', 30)
					.css('left', 0)
					.css('top', -30)
					.css('opacity',50)
					;
				elemTemplate.appendChild( elemTag );*/

			elemGrid = $.createElement( {type:'div', id:id + '_Grid', css:'', attr:{xGroup:'template', className:'grid',exPass:'1',exSizable:'1'}} );
				$(elemGrid).css('width', width-4 )
					.css('height', height-4)
					.css('opacity', 30);
				elemTemplate.appendChild( elemGrid );

			elemSA = $.createElement( {type:'div', id:id + '_SA', css:'', attr:{xGroup:'template', className:'safearea',exPass:'1',exSizable:'1'}} );
				$(elemSA).css('width', width-4)
					.css('height', height-4)
					.css('left', 0)
					.css('top', 0)
					.css('opacity', 50);
				elemTemplate.appendChild( elemSA );

			elemCode = $.createElement( {type:'div', id:id + '_Code', css:'', attr:{xGroup:'code', className:'code',exPass:'1',exSizable:'1'}} );
				$(elemCode).css('width', width-4)
					.css('height', height-4)
					.css('left', 0)
					.css('top', 0)
					.css('opacity2', 100)
					.hide();

			elemCodeArea = $.createElement( {type:'textarea', id:id + '_CodeArea', css:'', attr:{xGroup:'codearea', className:'codearea', exPass2:'1', exSizable2:'1'}} );
				$(elemCodeArea).css('width', width-12)
					.css('height', height-38)
					.css('left', 4)
					.css('top', 30)
					.css('opacity2', 100);
				elemCode.appendChild( elemCodeArea );

			elemTemplate.appendChild( elemCode );
		}
	},

	addComponent: function( P )
	{
		var compObj = new emsp_cms.Component( P );
		compObj.parentTemplate = this;

		// 添加到工作区
		this.elemTemplate.appendChild( compObj.elemComponent );

		// 添加到列表
		this.components[compObj.id] = compObj;
		Designer.atree_ElemStruct.rootItem.addItem( {id:compObj.id, text:compObj.id + ' (' + compObj.data.text + ')', autoExpand:1} );

		this.setCurrentComponent( compObj );
		Designer.control.setCurControl( compObj );
	},

	removeComponent: function( O )
	{
		if( O )
		{
			with( this )
			{
				$(O.elemComponent).anim({opacity:0},10,
					function()
					{
						components[O.id].parentTemplate.elemTemplate.removeChild( components[O.id].elemComponent );
						delete components[O.id];
					});
			}
		}

		return this;
	},

	// 设置当前模板
	setCurrentComponent: function( S )
	{
		with( this )
		{
			for( var i in components )
			{
				$(components[i].elemComponent).css('borderWidth', 0 );
			}

			if( S )
				$(S.elemComponent).css('border', '1px dashed #fff' );
			else
				lastComponent = null;

			curComponent = S;
		}
		return this;
	},

	getCurrentComponent: function()
	{
		return this.curComponent;
	},

	getProperty: function( P )
	{
		with( P )
		{
			return this[field] == undefined ? '' : this[field];
		}
	},

	setProperty: function( F, V )
	{
		with( this )
		{
			this[F] = V;
			if( $.validate.isCssAttr( F )) $(elemTemplate).css( F, V );

			switch( F )
			{
				case 'backgroundColor':
					if( V ) elemTemplate.style.backgroundColor = V;
					else elemTemplate.style.background = '';
					break;

				case 'backgroundImage':
					backgroundImage = V;
					elemTemplate.style.backgroundImage = 'url(' + V + ')';
					break;
			}
		}
	},

	showHtmlCode: function( A )
	{
		with( this )
		{
			A ? $(elemCode).show() : $(elemCode).hide();
			if( A )
			{
				elemCodeArea.innerText = Designer.workspace.genHtmlCode(this);
			}
		}

		return this;
	},

	showGrid: function( A )
	{
		with( this )
		{
			A ? $(elemGrid).show() : $(elemGrid).hide();
		}
	},

	showSA: function( A )
	{
		with( this )
		{
			A ? $(elemSA).show() : $(elemSA).hide();
		}
	},

	showAnim: function( A )
	{
		with( this )
		{
			m_showAnim = A;
		}
	},

	showComponent: function( A )
	{
		with( this )
		{
			for( var i in components )
			{
				A ? $(components[i].elemComponent).show() : $(components[i].elemComponent).hide();
			}
		}
	},

	snapToGrid: function( A )
	{
		with( this )
		{
			m_snapToGrid = A;
		}
	},

	getHtmlCode: function()
	{
		var E = '';
		with( this )
		{
			var o = $(elemTemplate);
			E = '<div id="' + id + '" name="' + id + '"\n\t'
				+ ' CMS_Class="CmsTemplate"' + '\n\t'
				+ ' style="left:0px;top:0px;width:' + width + 'px;height:' + height + 'px'
				+ ';color:' + color + ';background-color:' + backgroundColor
				+ ';background-image:' + ( backgroundImage ? 'url(' + backgroundImage + ')': '' )
				+ ';background-repeat:' + backgroundRepeat
				+ ';">\n';
		}
		return E;
	}
}

//
// 模板管理器
//
emsp_cms.TemplateManager = $.newClass();
emsp_cms.TemplateManager.prototype =
{
	constructor: function()
	{
		this.id = $.makeGlobalId( 'CmsTemplateManager' );

		this.templates = new Array();
		this.curTemplate = 0;
	},

	// 创建新模板
	createTemplate: function( P )
	{
		var tempObj = new emsp_cms.Template( P );
		tempObj.parentManager = this;

		// 添加到工作区
		Designer.workspace.elemWorkspace.appendChild( tempObj.elemTemplate );

		// 添加到列表
		this.templates[tempObj.id] = tempObj;
		this.setCurrentTemplate( tempObj );
	},

	// 删除模板
	deleteTemplate: function( T )
	{
		if( !T || T.classType != 'Template' ) return false;
		with( this )
		{
			if( !templates[T.id] )
			{
				alert( 'deleteTemplate(): Invalid index: ' + T.id );
				return false;
			}

			for( var i in T.components ) delete T.components[i];
			T.components.length = 0;

			delete templates[T.id];
			$.removeElement( T.elemTemplate );
		}

		return true;
	},

	// 设置当前模板
	setCurrentTemplate: function( S )
	{
		this.curTemplate = S;
		return this;
	},

	getCurrentTemplate: function()
	{
		return this.curTemplate;
	},

	repaint: function()
	{
		var x = Designer.workspace.factLeft,
			y = Designer.workspace.factTop;
		with( this )
		{
			for( var i in templates )
			{
				$(templates[i].elemTemplate).css('left', x).css('top', y);
				x += 20;
				y += 20;
			}
		}
	}
}

//
// 设计器
//
var Designer =
{
	// 通用控件成员
	previewWindow: 0
	,dlg_NewTemplate: 0
	,mmn_MainMenu: 0
	,sheets_ProjectWnd: 0
	,atree_ElemStruct: 0
	,lst_Componets: 0
	,proped_CurComp: 0
	,quickTips: 0
	,colorPicker: 0

	// CMS 控件成员
	,templateManager: 0

	//
	,templateId: -1

	// 辅助
	,aux:
	{
		about: function()
		{
			alert( 'TemplateDesigner 1.0.4.1 (build 20130612)\n\nCopyright (C) 2005-2013, EnRich Co.,Ltd.' );
		}

		,init: function()
		{
			$.measure.start();

			with( Designer )
			{
				// 对象初始化
				templateManager = new emsp_cms.TemplateManager();

				// 快速提示
				quickTips = new scumix.swat.spark.QuickTips();
				colorPicker = new scumix.swat.spark.ColorPicker();

				// 主菜单
				mmn_MainMenu = new scumix.swat.spark.MainMenu( {container:'eMenuBar', animSpeed:15} );
				mmn_MainMenu.addItem( DS_MainMenu );

				// 工作区
				workspace.elemWorkspace = $E('eWorkspace');
				workspace.elemHotCompIndicator = $E('eHotCompIndicator');
				$(workspace.elemHotCompIndicator).css('opacity', 60);

				// 初始化工作页
				sheets_ProjectWnd = new scumix.swat.spark.SheetGroup( {container:'eProjectWnd', animSpeed:1} );
				sheets_ProjectWnd
						.addSheet( {title:'模板属性', elem:['eSheet_TemplateProp']} )
						.addSheet( {title:'元素结构', elem:['eSheet_ElemStruct']} )
						.addSheet( {title:'组件', elem:['eSheet_Comp']} )
						.addSheet( {title:'属性', elem:['eSheet_CompProp']} )
						.showSheet(2);

				// 组件列表
				lst_Componets = new scumix.swat.spark.StackList( DS_Components, 'eSheet_Comp_Content' );

				// 属性编辑器
				proped_CurComp = new scumix.swat.spark.PropertyEditor( {container:'eSheet_CompProp', animSpeed:1} );

				// 元素结构树
				atree_ElemStruct = new scumix.swat.spark.ActiveTreeList( {container:'eSheet_ElemStruct', text:'全部元素', dragable: 0,
					onClick: function(S)
					{
						if( Designer.templateManager.curTemplate )
						{
							Designer.templateManager.curTemplate.setCurrentComponent( Designer.templateManager.curTemplate.components[S.id] );
						}
					}
					});
			}

			// 初始化组件面板
			var E = '', C, D = DS_Components.nodes;
			for( var i=0; i<D.length; i++ )
			{
				if( !D[i].comps ) continue;
				for( var j=0; j<D[i].comps.length; j++ )
				{
					C = D[i].comps[j];

					var gx = -C.glyph.x
						,gy = C.glyph.y
						,hint = C.hint || '';

					var compId = 'eCOMP_' + D[i].id + '_' + j;
					var oComp = $.createElement({type:'div',id:compId,css:'',attr:{className:'CMS_ComponentItem',title:hint}});
					var oIcon = $.createElement({type:'div',id:compId+'_Icon',css:'',attr:{className:'CMS_ComponentItem_Icon',exDragable:1,xCompGID:i,xCompID:C.id}});
						oIcon.style.background = 'url(' + D[i].glyphSrc + ') no-repeat ' + gx + ' ' + gy;
						oIcon.onmouseover = function(){ this.style.backgroundPositionY=-48 }
						oIcon.onmouseout = function(){ this.style.backgroundPositionY=0 }
						oIcon.onclick = function(){ Designer.workspace.addComponent(this) }
						oIcon.OnMove = function( evt, S )
						{
							$(Designer.workspace.elemHotCompIndicator).show();
							Designer.workspace.elemHotCompIndicator.xSrcCompElem = S;
							with( Designer.workspace.elemHotCompIndicator.style )
							{
								left = evt.clientX - 24;
								top = evt.clientY - 24;
								background = S.style.background;
								//cursor = 'not-allowed';
							}

							if( $(Designer.workspace.curTempWnd).ptIn( evt ))
							{
								//Designer.workspace.elemHotCompIndicator.style.cursor = 'default';
							}
						}
					oComp.appendChild( oIcon );
					var oText = $.createElement({type:'div',id:compId+'_Text',css:'',attr:{className:'CMS_ComponentItem_Text'}});
						oText.innerHTML = C.text;
					oComp.appendChild( oText );

					$E(D[i].content).appendChild( oComp );
				}

				// 放下组件事件
				Designer.workspace.elemHotCompIndicator.onmouseup = function()
				{
					evt = $.getEvent();
					$(this).hide();

					// 若在当前模板区内放下, 则添加组件
					var o = $(Designer.templateManager.curTemplate.elemTemplate);
					if( o.ptIn( evt ))
					{
						Designer.templateManager.curTemplate.addComponent({
								groupID: this.xSrcCompElem.xCompGID,
								compID: this.xSrcCompElem.xCompID,
								left: evt.clientX - o.css('left'),
								top: evt.clientY - o.css('top')
								});
					}
				}
			}

			var w = document.body.clientWidth,
				h = document.body.clientHeight;
			var msg = '您的浏览器分辨率为 ' + w + '×' + h;
				if( w < 1280 || h < 768 ) msg += ', 要获取较好的操作体验, 请调高分辨率!';
			Designer.quickTips.warning( msg );
		}

		,browseResource: function( T )
		{
			var w = window.showModalDialog( 'ResourceExplorer.html', window, 'dialogWidth:1000px;dialogHeight:600px;status:0;center:1;resizable:0' );
			return __popWindowResult;
		}
	},

	// 全局键盘事件处理
	keybHandler: function( E )
	{
		E = E || window.event;
		var K = E.keyCode;
		switch( K )
		{
			/*case 116: // F5
				Designer.workspace.alignUI();
				return false;
				break;*/

			case 32:
				Designer.workspace.updateWorkspaceInfo();
				return false;
				break;

			case 78: // N
				if( E.altKey ) Designer.dlg_NewTemplate.show();
				break;

			case 82: // R
				if( E.altKey ) Designer.workspace.alignUI();
				break;

			case 46: // DELETE
				Designer.control.removeCurControl(1);
				break;

			case 113:
			case 115:
				Designer.aux.toggleUIMode();
				break;

			/*case 13: // RETURN
				Designer.quickTips.info( '运行时间 ' + $.measure.elapsed() + ' 毫秒' );
				break;*/

			/*
			case 48+1:
				Designer.sheets_ProjectWnd.showSheet(0);
				break;

			case 48+2:
				Designer.sheets_ProjectWnd.showSheet(1);
				break;

			case 48+3:
				Designer.sheets_ProjectWnd.showSheet(2);
				break;

			case 48+4:
				Designer.sheets_ProjectWnd.showSheet(3);
				break;
			*/

			case 192: // `
				Designer.mmn_MainMenu.items.mn_View.items.mn_View_ShowHtmlCode.onClick( Designer.mmn_MainMenu.items.mn_View.items.mn_View_ShowHtmlCode );
				break;

			case 37: // LEFT
				Designer.control.moveCurControl('L');
				break;

			case 39: // RIGHT
				Designer.control.moveCurControl('R');
				break;

			case 38: // UP
				Designer.control.moveCurControl('U');
				break;

			case 40: // DOWN
				Designer.control.moveCurControl('D');
				break;

			//default: alert(K);$ERR(K); return false;
		}
	},

	// 控件
	control:
	{
		lastControl: 0,	// 最后操作的控件
		curControl: 0,	// 当前操作的控件

		// 设置当前控件
		setCurControl: function( S )
		{
			with( this )
			{
				if( lastControl != S )
				{
					lastControl = S;
					curControl = S;
					if( S )
					{
						switch( S.classType )
						{
							case 'Template':
								Designer.workspace.updateTemplateProperty( S );
								break;

							case 'Component':
								Designer.workspace.updateComponentProperty( S );
								Designer.atree_ElemStruct.rootItem.setCurItem( Designer.atree_ElemStruct.rootItem.getChildByProperty( 'id', S.id ));
								break;
						}
					}
				}
			}

			return this;
		},

		// 更新控件属性
		updateProperty: function( P )
		{
			return Designer.proped_CurComp.updateProperty( P );
		},

		// 移除当前控件
		removeCurControl: function( A )
		{
			with( this )
			{
				//if( $.getTarget().id != curControl.id ) return this;
				if( !curControl ) return this;
				switch( curControl.classType )
				{
					case 'Component':
					{
						var ctrlInfo = '类型: 组件\n类别: ' + curControl.data.text + '\nID: ' + curControl.id;

						if( A )
						{
							if( !confirm( '是否要删除以下控件?\n\n' + ctrlInfo )) break;
						}

						Designer.workspace.removeComponent();
						Designer.quickTips.info( '控件已删除 (' + ctrlInfo + ')' );
					} break;
				}
			}

			return this;
		},

		// 移动当前控件
		//??
		moveCurControl: function( A )
		{
			with( this )
			{
				//if( $.getTarget().id != curControl.id ) return this;
				if( !curControl ) return this;
				var E = $.getEvent(), step = E.ctrlKey ? 10 : 1, isResize = E.shiftKey ? 1 : 0;
				switch( A )
				{
					case 'L':
						isResize ?
							curControl.setProperty( 'width', Math.max( curControl.width - step, 1 ))
							:
							curControl.setProperty( 'left', curControl.left - step );
						break;

					case 'R':
						isResize ?
							curControl.setProperty( 'width', curControl.width + step )
							:
							curControl.setProperty( 'left', curControl.left + step );
						break;

					case 'U':
						isResize ?
							curControl.setProperty( 'height', Math.max( curControl.height - step, 1 ))
							:
							curControl.setProperty( 'top', curControl.top - step );
						break;

					case 'D':
						isResize ?
							curControl.setProperty( 'height', curControl.height + step )
							:
							curControl.setProperty( 'top', curControl.top + step );
						break;
				}

				//Designer.quickTips.info( curControl.left );
			}

			return this;
		}
	},

	// 工作区
	workspace:
	{
		 elemWorkspace: 0
		,elemHotCompIndicator: 0

		,compInstanceId: 0
		,factLeft: 0
		,factTop: 0
		,showGrid: 1
		,showSA: 1
		,gridSize: 10
		,showSA: 1
		,hotCompIndi: 0
		,uiMode: 0

		// 重排界面
		,alignUI: function()
		{
			var	dw = document.body.clientWidth,
				dh = document.body.clientHeight;

			$('eWorkspace').resizeTo( dw, dh );
			$('eToolBar').resizeTo( dw, 80 ).moveTo( 0, 0 );
			$('eProjectWnd').resizeTo( 280, dh - $('eToolBar').css('height') - 42).moveTo( 0, $('eToolBar').css('height') + 1 );

			with( this )
			{
				factLeft = $('eProjectWnd').css('width') + 5;
				factTop = $('eToolBar').css('height') + 5;
				if( Designer.templateManager ) Designer.templateManager.repaint();
			}
		}

		// 切换界面显示状态
		,toggleUIMode: function()
		{
			with( this )
			{
				uiMode = 1 - uiMode;
				uiMode ? $('eToolBar,eMenuBar,eProjectWnd').hide() : $('eToolBar,eMenuBar,eProjectWnd').show();
			}
		}

		,toggleShowGrid: function()
		{
			with( this )
			{
				var e = Designer.templateManager.curTemplate.elemGrid;
				if( e )
				{
					showGrid = 1 - showGrid;
					showGrid ? $(e).show() : $(e).hide();
				}
			}
		}

		,toggleShowSA: function( S )
		{
			with( this )
			{
				var e = Designer.templateManager.curTemplate.elemSA;
				if( e )
				{
					showSA = 1 - showSA;
					showSA ? $(e).show() : $(e).hide();
				}
			}
		}

		,addComponent: function( S )
		{
			if( !Designer.templateManager.curTemplate ) return false;
			if( Designer.templateManager.curTemplate.m_showAnim )
			{
				var e = $.getEvent();
				Designer.workspace.elemHotCompIndicator.style.background = S.style.background;
				$(Designer.workspace.elemHotCompIndicator)
					.show()
					.moveTo(e.clientX,e.clientY)
					.anim({
							left:$(Designer.templateManager.curTemplate.elemTemplate).css('left'),
							top:$(Designer.templateManager.curTemplate.elemTemplate).css('top')},
							15,
							function()
							{
								Designer.templateManager.curTemplate.addComponent( {groupID: S.xCompGID, compID:S.xCompID} );
								$(Designer.workspace.elemHotCompIndicator).hide();
							})
					;
			}
			else
			{
				Designer.templateManager.curTemplate.addComponent( {groupID: S.xCompGID, compID:S.xCompID} );
			}
		}

		,removeComponent: function()
		{
			with( Designer.templateManager )
			{
				if( curTemplate )
				{
					Designer.atree_ElemStruct.curItem.removeItem();
					curTemplate.removeComponent( curTemplate.curComponent );
					Designer.control.setCurControl( null );
				}
			}
		}

		,updateWorkspaceInfo: function()
		{
			with( Designer.templateManager )
			{
				if( !curTemplate ) return;

				Designer.quickTips.info(
						'工作空间中共 ' + $.getObjectLength(Designer.templateManager.templates) + ' 个模板'
						+ '<br>当前模板: id=' + curTemplate.id + ', 名称=' + curTemplate.templateName + ', 共 ' + $.getObjectLength( curTemplate.components ) + ' 个组件'
						+ '<br>当前组件: ' + ( curTemplate.curComponent ? curTemplate.curComponent.id + '(' + curTemplate.curComponent.data.text + ')' : '(none)' )
						+ '<br>当前控件: ' + 'id: ' + ( Designer.control.curControl ? Designer.control.curControl.id : '(none)' )
						, 150 );
			}
		}

		,updateComponentProperty: function( S )
		{
			Designer.proped_CurComp.clear();
			var D = DS_ComponentProperty.properties;
			for( var i in D )
			{
				Designer.proped_CurComp.addProperty( D[i], S );
			}

			for( var i in S.data.properties )
			{
				Designer.proped_CurComp.addProperty( S.data.properties[i], S );
			}
		}

		,updateTemplateProperty: function( S )
		{
			Designer.proped_CurComp.clear();
			var D = DS_TemplateProperty.properties;
			for( var i in D )
			{
				Designer.proped_CurComp.addProperty( D[i], S );
			}
		}

		,genHtmlCode: function( T )
		{
			T = T || Designer.templateManager.curTemplate;
			if( !T ) return '';

			with( T )
			{
				// 生成 HTML
				E  = DS_Code.html.HTML_BEGIN;

				E += DS_Code.html.CSS_BEGIN;
				E += DS_Code.html.CSS_CONTENT
						.replace( '{%$TemplateWidth%}', $(elemTemplate).css('width') )
						.replace( '{%$TemplateHeight%}', $(elemTemplate).css('height') );
				E += DS_Code.html.CSS_END;

				// JS
				E += DS_Code.html.SCRIPT_IMPORT;
				/*E += '\nvar $G_InitRoution=[';
				for( var it in components )
				{
					E += components[it].getJsCode('init') + ',';
				}
				E = E.trim(',');
				E += ']';

				for( var it in components )
				{
					var C = components[it];
					E += '\n' + C.getJsCode();
				}
				*/
				E += DS_Code.html.SCRIPT_BEGIN;
				E += DS_Code.html.SCRIPT_END;

				E += DS_Code.html.BODY_BEGIN;

				// 组件扩展 JS
				for( var it in components )
				{
					E += components[it].getJsCode('import') + '\n';
				}

				//??
				E += getHtmlCode();

				// 组件
				for( var it in components )
				{
					var C = components[it];
					E += '\n' + C.getHtmlCode();
				}

				E += DS_Code.html.BODY_END;
				E += DS_Code.html.HTML_END;

				return E;
			}
		}

		,closeTemplate: function( T )
		{
			T = T || Designer.templateManager.curTemplate;
			if( !T ) return false;

			var ctrlInfo = '类型: 模板\nID: ' + T.id;
			if( !confirm( '是否要删除以下模板?\n\n' + ctrlInfo )) return false;

			Designer.atree_ElemStruct.clear();
			Designer.templateManager.deleteTemplate( T );
			Designer.templateManager.setCurrentTemplate( null );
			Designer.control.setCurControl( null );
			Designer.quickTips.info( '模板已删除 (' + ctrlInfo + ')' );

			return true;
		}

		,previewTemplate: function( T )
		{
			T = T || Designer.templateManager.curTemplate;
			if( !T ) return false;

			with( Designer )
			{
				T.elemCodeArea.innerText = this.genHtmlCode( T );

				if( previewWindow == 0 || previewWindow.closed )
				{
					previewWindow = window.open( '', '_blank', 'width=' + T.width + ',height=' + T.height );
				}

				previewWindow.focus();
				previewWindow.document.write( T.elemCodeArea.innerText );
				previewWindow.document.close();
			}

			return true;
		}

		,newTemplate: function()
		{
			Designer.templateManager.createTemplate(
				{
					templateName: '未命名',
					alias: 'Untitled',
					author: 'admin',
					desc: 'no desc',
					layout: 0,
					definition: 'HD',
					width: 1280,
					height: 720
				});
		}

		,loadTemplate: function( id )
		{
			Designer.quickTips.info( '从服务器读取模板数据 (ID=' + id + ')...' );

			// 从服务器读取
			if( 1 )
			{
				id = id || 1;
				$.ajax.load
				({
					 url: DS_Config.interfaces.template.load
					,param: 'id=' + id
					,onData: function(R)
					{
						try
						{
							//alert(R);
							eval( 'var json=' + R );
							if( !json.success )
							{
								Designer.quickTips.info( '载入模板失败! (' + json.msg + ')' );
								return false;
							}
							else
							{
								// 创建模板及组件
								with( json.data )
								{
									json.data.isNewCreate = 0;
									Designer.templateManager.createTemplate( json.data );
									for( var i in components )
									{
										components[i].isNewCreate = 0;
										Designer.templateManager.curTemplate.addComponent( components[i] );
									}

									Designer.quickTips.info( '模板载入成功! (模板名称: ' + json.data.templateName + ', 共 ' + components.length + ' 个组件)', 200, 1 );
								}
							}
						}
						catch( E )
						{
							alert( '载入模板失败:\n\n' + $.errorString( E ));
						}
					}
				});
			}

			return true;
		}

		// 保存模板
		,saveTemplate: function( id )
		{
			// 未选中任何模板, 则返回
			if( !Designer.templateManager.curTemplate ) return false;

			with( Designer.templateManager.curTemplate )
			{
				// 持久化(模板+模板中的组件)
				var persistentData = $.json.toJson( $.persistent.getPersistentObject( Designer.templateManager.curTemplate ));
				persistentData = persistentData.trim('},') + ',components:[';
				for( var i in components )
				{
					 persistentData += $.json.toJson( $.persistent.getPersistentObject( components[i] )) + ',';
				}
				persistentData = persistentData.trim( ',' ) + ']}';
				//alert(persistentData);
				//elemCodeArea.innerText = persistentData;

				// 生成数据对象
				var saveObj =
				{
					version:'1.0'
					,objectId:id
					,db_field:
					{
						fname: templateName,
						falias: alias,
						fauthor: author,
						fdesc: desc,
						fwidth: width,
						fheight: height,
						flayout: layout,
						fdefinition: definition
					}
				}

				// 编辑保存
				if( Designer.templateId > -1 ) saveObj.db_field.id = Designer.templateId;

				// 更新代码编辑区
				if( !Designer.mmn_MainMenu.items.mn_View.items.mn_View_ShowHtmlCode.checked )
				{
					elemCodeArea.innerText = this.genHtmlCode();
				}

				else
				{
					if( !confirm( "您已经切换到手工代码编辑模式, 在保存前请确认代码正确。\n\n您确定要继续保存吗?" )) return false;
				}

				// 拼接 POST 数据
				var postData =
						$.urlParam.toQueryString( saveObj.db_field )
						+ '&fhtmldata=' + encodeURIComponent( elemCodeArea.innerText )
						+ '&frawdata=' + encodeURIComponent( persistentData );
				//alert( postData ); return;

				// 保存至服务器
				if( 1 )
				{
					Designer.quickTips.info( '保存至服务器 (' + DS_Config.interfaces.template.save + ')...' );

					$.ajax.load
					({
						 url: DS_Config.interfaces.template.save
						,param: postData
						,onData: function( R )
						{
							try
							{
								eval( 'var json=' + R );
								if( json.success )
								{
									Designer.templateId = json.data.id;
									Designer.quickTips.info( '保存成功! (ID=' + Designer.templateId + ')', 0, 1 );
								}
								else
								{
									Designer.quickTips.info( '保存失败! ' + json.msg, 0, 1 );
								}
							}
							catch( E )
							{
								alert( $.errorString( E ));
							}
						}
					});
				}
			}
		}
	}
}

$.pageResize( function()
{
	Designer.workspace.alignUI();
})

$.pageReady( function()
{
	// 初始化
	with( Designer )
	{
		$E('eSheet_ElemStruct').style.width = '274px';
		workspace.alignUI();
		aux.init();

		lst_Componets.expandeAll();

		// 对话框
		//var dlgfrm = new scumix.swat.spark.border.Box9ng( 'eDialog_NewTemplate', {elem:'eDialogContent_NewTemplate', enableAnim:2});
		dlg_NewTemplate = new scumix.swat.spark.Dialog( null,
			{
				title:'创建新模板',
				elem:'eDialog_NewTemplate',
				enableAnim:0,
				width:642,
				height:450,
				border: 0
			});
	}

	// 绑定 UI 事件
	$('eToolBar').event('move', function()
		{
			var o = $(this),
				x = o.css('left'),
				y = o.css('top');
			$('eMenuBar').moveTo( x + 25, y + 48 );
		});

	$('btn_NewTemplate_Ok').event( 'click', function()
		{
			Designer.dlg_NewTemplate.close();
			Designer.quickTips.warning('新模板已建立');

			Designer.templateManager.createTemplate(
				{
					templateName: $E('ed_NewTemp_Name').value,
					alias: $E('ed_NewTemp_Name').value,
					author: $E('ed_NewTemp_Author').value,
					desc: $E('ed_NewTemp_Desc').value,
					layout: 0,
					definition: 'HD',
					width:$E('ed_NewTemp_Width').value,
					height:$E('ed_NewTemp_Height').value
				});
		});

	$('eCMSLogo').event('click',
		function()
		{
			Designer.aux.about();
			//Designer.colorPicker.show(this);
		});

	document.onkeydown = Designer.keybHandler;

	Designer.quickTips.info( '系统初始化完成, 共耗时 ' + $.measure.elapsed() + ' 毫秒' );

	$('btn_QuickLoadTemp,btn_QuickSaveTemp,btn_QuickNewTemp,btn_QuickPreviewTemp,btn_QuickCloseTemp')
		.attr('className', 'CMS_Button_Normal' )
		.event('mouseover',
			function(S)
			{
				$(this).attr('className', 'CMS_Button_Normal_over' );
			})
		.event('mouseout',
			function(S)
			{
				$(this).attr('className', 'CMS_Button_Normal' );
			})
		.event('mousedown',
			function(S)
			{
				$(this).attr('className', 'CMS_Button_Normal_down' );
			})
		.event('mouseup',
			function(S)
			{
				$(this).attr('className', 'CMS_Button_Normal' );
			});

	//
	$.urlParam.paramString( location.search.substr(1));
	Designer.templateId = $.urlParam.param('id');
	if( Designer.templateId > -1 )
	{
		//alert( '编辑模板: templateId=' + Designer.templateId );
		Designer.workspace.loadTemplate( Designer.templateId );
	}
})

</script>

<body>

<!--工作区-->
<div id="eWorkspace"></div>

<!--工具栏-->
<div id="eToolBar"
	exDragable="1" exTopOnDrag="1">

	<!--主面板-->
	<div id="ePanel_Menu"
	class="Panel_H"
	exPass="1">

		<!--Logo 按钮-->
		<div id="eCMSLogo"
			style="position:absolute;left:8px;top:4px;width:142px;height:37px;background:url(assets/images/cms_logo_btn.png) no-repeat 0 0"
			onmouseover="this.style.backgroundPositionY=-37"
			onmouseout="this.style.backgroundPositionY=0"
			onmousedown="this.style.backgroundPositionY=-74"
			onmouseup="this.style.backgroundPositionY=-37"></div>
	</div>

	<!--快捷工具栏-->
	<div id="ePanel_QuickBar"
		class="Panel_H"
		exPass="1">
		<div style="margin:5px 20px 0px 10px">
		<button id="btn_QuickNewTemp" onclick="Designer.workspace.newTemplate()">快速新建模板</button>
		<button id="btn_QuickSaveTemp" onclick="Designer.workspace.saveTemplate()">保存模板</button>
		<button id="btn_QuickLoadTemp" onclick="Designer.workspace.loadTemplate()">加载模板</button>
		<button id="btn_QuickCloseTemp" onclick="Designer.workspace.closeTemplate()">删除模板</button>
		<button id="btn_QuickPreviewTemp" onclick="Designer.workspace.previewTemplate()">预览</button>
		</div>
	</div>

	<!--信息面板-->
	<div style="float:left">
		<div id="ePanel_Info"
			class="Panel_H"
			exPass="1">
			<div id="eInfo" style="margin-left:8px;width:100%;height:100%;font:normal 12px Consolas;color:#ccc;cursor:default" exPass="1"></div>
		</div>

		<div id="ePanel_Info"
			class="Panel_H"
			exPass="1" style="float:left;clear:left">
		</div>
	</div>
</div>

<!--菜单-->
<div id="eMenuBar"></div>

<!--工程信息窗口-->
<div id="eProjectWnd"
	class="Panel_V"
	exDragable="1" exTopOnDrag="1" exSizable="0" exSizeDir="LR">

	<!--工作页-->
	<div id="eSheet_TemplateProp"
		class="eProjectWnd_Sheet"
		exDragable='1' exPass='1'></div>

	<div id="eSheet_ElemStruct"
		class="eProjectWnd_Sheet"></div>

	<div id="eSheet_Comp"
		class="eProjectWnd_Sheet">
		<div style="height:5px;font-size:0px"
			xTag="0"
			onclick="this.xTag = 1 - this.xTag; this.xTag == 1 ? Designer.lst_Componets.expandeAll() : Designer.lst_Componets.collapseAll()"></div>
		<div id="eSheet_Comp_Content"></div>
	</div>

	<div id="eSheet_CompProp"
		class="eProjectWnd_Sheet"></div>

</div>

<!--组件控件容器-->
<div id="eComp_Layout" class=""></div>
<div id="eComp_Text" class=""></div>
<div id="eComp_Control" class=""></div>
<div id="eComp_Media" class=""></div>
<div id="eComp_Extension" class=""></div>

<!--组件拖动指示器-->
<div id="eHotCompIndicator"></div>

<!--Dialog BEGIN 新建模板-->
<div id="eDialog_NewTemplate" class="SxDialog" exDragable="1" exPass="1" style="background:#34383e;padding:30px">
	<div class="CMS_CtrlRow">
		<div class="caption">模板名称:</div><div><input id="ed_NewTemp_Name" type="text" value="untitled"/></div>
	</div>
	<div class="CMS_CtrlRow">
		<div class="caption">模板宽度:</div>
		<div><input id="ed_NewTemp_Width" type="text" value="1024" style="width:60px"/></div>
		<div class="cap2">模板高度:</div>
		<div><input id="ed_NewTemp_Height" type="text" value="768" style="width:60px"/></div>
	</div>
	<div class="CMS_CtrlRow">
		<div class="caption">搜索标签:</div><div><input id="ed_NewTemp_SearchKey" type="text" value=""/></div>
	</div>
	<div class="CMS_CtrlRow">
		<div class="caption">作者:</div><div><input id="ed_NewTemp_Author" type="text" value="admin"/></div>
	</div>
	<div class="CMS_CtrlRow">
		<div class="caption">模板说明:</div><div><textarea id="ed_NewTemp_Desc" rows="5" style="overflow:hidden"></textarea></div>
	</div>
	<div class="CMS_CtrlRow" style="margin-top:50px">
		<button id="btn_NewTemplate_Ok">确定</button><button onclick="Designer.dlg_NewTemplate.hide()">取消</button>
	</div>
</div>
<!--Dialog END 新建模板-->

</body>
</html>

